package com.truyen.persistence.dao.impl;

import java.util.List;

import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.truyen.persistence.dao.LogJsoupDao;
import com.truyen.persistence.dao.base.GenericJpaBaseDaoImpl;
import com.truyen.persistence.entity.LoaiLog;
import com.truyen.persistence.entity.LogJsoup;
import com.truyen.utils.PagingInfo;

@Repository
public class LogJsoupDaoImpl extends GenericJpaBaseDaoImpl<LogJsoup, Long>
		implements LogJsoupDao {

	public LogJsoupDaoImpl() {
		super(LogJsoup.class);
	}

	@Override
	public List<LogJsoup> getLstLog(String sort, String sortBy,
			LoaiLog loaiLog, PagingInfo pInfo) {
		CriteriaBuilder critBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<LogJsoup> query = critBuilder
				.createQuery(LogJsoup.class);
		Root<LogJsoup> entity = query.from(LogJsoup.class);
		Predicate p = critBuilder.conjunction();
		p = critBuilder.and(p,
				critBuilder.equal(entity.<LoaiLog> get("loaiLog"), loaiLog));
		query = query.where(p);
		if(sort.equals("desc")){
			query.orderBy(critBuilder.desc(entity.get(sortBy)));
		}else{
			query.orderBy(critBuilder.asc(entity.get(sortBy)));
		}
		TypedQuery<LogJsoup> q = entityManager.createQuery(query);
		long count = countByQuery(query, entity);
		pInfo.setCount(count);
		pInfo.setTotalPage((int)Math.ceil((double)count/pInfo.getSizePerPage()));		
		q.setFirstResult(pInfo.getStartResult());
		q.setMaxResults(pInfo.getSizePerPage());
		List<LogJsoup> lst = q.getResultList();
		return (lst.size() > 0) ? lst : null;
	}

}
